package com.sand.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sand.entity.CollectionEntity;
import com.sand.entity.UserattachmentEntity;
import com.sand.entity.UserdetailsEntity;
import com.sand.entity.UserinfoEntity;
import com.sand.service.IAppoinService;
import com.sand.service.IUserInfoService;
import com.sand.service.IWithdrawalService;
import com.sand.util.FileUpLoad;
import com.sand.util.ModelTest;
import com.sand.util.PageModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import static com.sand.mobilever.SDKTestSendTemplateSMS.sendMesModel;

@Controller
@RequestMapping(value = "userInfo")
public class UserInfoController {
/**
 *用户接口
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/11/26/026 14:40
 */
    //IUserInfoService接口
    @Resource(name = "iUserInfoService")
    private IUserInfoService iUserInfoService;
    //withdrawalService接口
    @Resource(name = "withdrawalService")
    private IWithdrawalService withdrawalService;
    //withdrawalService接口
    @Resource(name = "apporinService")
    private IAppoinService appoinService;

    //前端登录
    @RequestMapping("/UserInfoLoging")
    public void queryLogin(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        HttpSession session = request.getSession();
        response.setCharacterEncoding("UTF-8");
        String code=session.getAttribute("code").toString();
        int spa=0;
        if(!code.equals(request.getParameter("verify").toLowerCase())){
            System.out.println(request.getParameter("verify"));
            response.getWriter().write("2");
            return;
        }
        if(request.getParameter("spa")!=null && !"".equals(request.getParameter("spa"))){
            spa=Integer.parseInt(request.getParameter("spa"));
        }
        HashMap<String,Object>  drom= iUserInfoService.login(request.getParameter("UserInfoName"),request.getParameter("UserInfoPwd"));
        if(drom!=null){
            if(spa==1){
                if(Integer.parseInt(drom.get("isHouse").toString())==1){
                    drom.put("loginMethod",1);
                    request.getSession().setAttribute("drom",drom);
                    request.getSession().setAttribute("drom1",drom.get("rid"));
                    response.getWriter().write(JSON.toJSON(drom).toString());
                }else {
                    response.getWriter().write("3");
                }
            }else{
                drom.put("loginMethod",0);
                request.getSession().setAttribute("drom",drom);
                request.getSession().setAttribute("drom1",drom.get("rid"));
                response.getWriter().write(JSON.toJSON(drom).toString());
            }

       }else {
           response.getWriter().write("1");
       }

    }

    //前台注册手机号验证码
    @RequestMapping("RegistrationVerification")
    public void RegistrationVerification(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String Number = request.getParameter("phoneNumber");
        if(!isInteger(Number)){
            response.getWriter().write("1");
        }else {
            String randcode = sendMesModel(Number);
            response.getWriter().write(randcode);
            //加入时间搓验证时间是否超时
            request.getSession().setAttribute("phoneRandCode",randcode+"#"+new Date().getTime());
        }

    }

    //注册
    @RequestMapping("register")
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(!iUserInfoService.addUserInfo(request.getParameter("json"))){
            response.getWriter().write("1");
        }
    }
    //前台页面跳转
    @RequestMapping("preset")
    public String prest(HttpServletRequest request, HttpServletResponse response,Model model){
        List<String> list = new ArrayList<String>();
        list.add(request.getParameter("districtName"));
        list.add(request.getParameter("price"));
        list.add(request.getParameter("houseType"));
        list.add(request.getParameter("constructionArea"));
        list.add(request.getParameter("paymentMethod"));
        list.add(request.getParameter("towards"));
        list.add(request.getParameter("housePicture"));
        list.add(request.getParameter("renovationCondition"));
        list.add(request.getParameter("phone"));
        list.add(request.getParameter("communityName"));
        list.add(request.getParameter("userId"));
        list.add(request.getParameter("rid"));
        model.addAttribute("list",list);
        return "/renting/pages/onther/preset";
    }
    //预约添加
    @RequestMapping("Appoin")
    public void  addAppoin( String text ,HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean b = appoinService.addAppoin(text);
        if (b){
            response.getWriter().write("1");
            return;
        }
        response.getWriter().write("0");
    }

    //收藏
    @RequestMapping("addCollection")
    public void addCollection(HttpServletRequest request, HttpServletResponse response,String data ) throws IOException {
        CollectionEntity coll = JSON.parseObject(data, CollectionEntity.class);
        boolean all = iUserInfoService.all(coll.getUserId(), coll.getHouseId());
        if(!all){
            boolean b = iUserInfoService.addCollection(data);
            response.getWriter().write("1");
        }else {
            iUserInfoService.ushou(data);
            response.getWriter().write("0");
        }

    }
    //判断是否为整数
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }


    //===============================  后台  ===============================

    //分页查询客户
    @RequestMapping(value = "/queryUserInfoLimit")
    public void queryUserInfoLimit(int limit,int page,String condition,HttpServletRequest request,HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");
        PageModel<HashMap<String,Object>> pm = iUserInfoService.queryUserInfoLimit(limit, page, condition);
        ModelTest<List<HashMap<String,Object>>> listData = new ModelTest<List<HashMap<String,Object>>>("OK",pm.getList(),0, pm.getPagecount());
        response.getWriter().write(JSON.toJSON(listData).toString());
    }
    //分页查询客户
    @RequestMapping(value = "/queryUserInfoById")
    public ModelAndView queryUserInfoById(int rid){
        return new ModelAndView("/layui/page/table_userInfo_show").addObject("userInfoShow",iUserInfoService.queryUserInfoById(rid));
    }
    //分页查询提现记录
    @RequestMapping(value = "/queryWithdrawalLimit")
    public void queryWithdrawalLimit(int limit,int page,String condition,HttpServletRequest request,HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");

        PageModel<HashMap<String,Object>> pm = withdrawalService.queryWithdrawalLimit(limit, page, condition);
        ModelTest<List<HashMap<String,Object>>> listData = new ModelTest<List<HashMap<String,Object>>>("OK",pm.getList(),0, pm.getPagecount());
        response.getWriter().write(JSON.toJSON(listData).toString());
    }
    //根据id查询所有所有收藏记录
    @RequestMapping(value = "/queryCollectionEntityById")
    public ModelAndView queryCollectionEntityById(int rid){
        return new ModelAndView("/layui/page/table_collection_show").addObject("list",iUserInfoService.queryCollectionEntityById(rid));
    }
    //分页查询预约记录
    @RequestMapping(value = "/queryAppoinLimit")
    public void queryAppoinLimit(int limit,int page,String condition,HttpServletRequest request,HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");

        PageModel<HashMap<String,Object>> pm = appoinService.queryAppoinLimit(limit, page, condition);
        ModelTest<List<HashMap<String,Object>>> listData = new ModelTest<List<HashMap<String,Object>>>("OK",pm.getList(),0, pm.getPagecount());
        response.getWriter().write(JSON.toJSON(listData).toString());
    }
    //根据id查询预约详情
    @RequestMapping(value = "queryAppoinById")
    public ModelAndView queryAppoinById(int rid)throws Exception{
        return new ModelAndView("/layui/page/table_appoin_show").addObject("appoinShow",appoinService.queryAppoinById(rid));
    }
    /**
     * 前端房东订单信息分页查询
     * @param limit
     * @param page
     * @param condition
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/queryAppointByUserIdLimit")
    public void queryAppointByUserIdLimit(int limit,int page,String condition,HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");
        PageModel<HashMap<String, Object>> model = appoinService.queryAppointByUserIdLimit(limit, page, condition);
        response.getWriter().write(JSON.toJSON(model).toString());
        System.out.println(JSON.toJSON(model).toString());
    }

    /**
     * 租客看房信息
     * @param limit
     * @param page
     * @param condition
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/queryTenantHouseViewLimit")
    public void queryTenantHouseViewLimit(int limit,int page,String condition,HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setCharacterEncoding("utf-8");
        PageModel<HashMap<String, Object>> model = iUserInfoService.queryTenantHouseViewLimit(limit, page, condition);
        response.getWriter().write(JSON.toJSON(model).toString());

        System.out.println(JSON.toJSON(model).toString());
    }

    //====================lyl=====================
    //执行数据更新
    @RequestMapping("/updateUser")
    @ResponseBody
    public String updateUserData(@RequestParam("name") String name,
                                 @RequestParam("sex") int sex,
                                 @RequestParam("phone") String phone,
                                 @RequestParam("idcode") String idcode,
                                 @RequestParam("opration") String opration,
                                 HttpServletRequest request){

        //解析传入的参数【多次更新数据需要】
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(opration);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject = null;
        }
        //获取登陆用户的信息
        HashMap loginMap = null;
        if(request.getSession().getAttribute("drom")!=null){
            loginMap = (HashMap) request.getSession().getAttribute("drom");
        }
        //设置传参对象
        JSONObject json = new JSONObject();
        //设置保存对象
        UserinfoEntity userinfo = new UserinfoEntity();
        UserdetailsEntity userdetails = new UserdetailsEntity();

        if(loginMap==null){
            json.put("statecode",1);
            json.put("msg","您没有登陆！");
        }else{
            userinfo.setCreateTime((Timestamp) loginMap.get("createTime"));
            userinfo.setIsAttest((int) loginMap.get("isAttest"));
            userinfo.setIsHouse((int) loginMap.get("isHouse"));
            //二次更新通过结合最后的参数
            if(jsonObject!=null){
                userinfo.setPassword(jsonObject.get("password")==null?loginMap.get("password").toString():jsonObject.get("password").toString());
            }else{
                userinfo.setPassword(loginMap.get("password").toString());
            }
            userinfo.setRid((int)loginMap.get("rid"));
            userinfo.setPhone(phone);

            //设置详细信息表
            userdetails.setName(name);
            userdetails.setUserId(userinfo.getRid());
            //单次更新调用
            if(jsonObject!=null){
                userdetails.setAvater(jsonObject.get("avater")==null?loginMap.get("avater")==null?null:loginMap.get("avater").toString():jsonObject.get("avater").toString());
            }else{
                userdetails.setAvater(loginMap.get("avater")==null?null:loginMap.get("avater").toString());
            }
            //userdetails.setAvater(loginMap.get("avater")==null?null:loginMap.get("avater").toString());
            if(jsonObject==null){
                userdetails.setJobInfo(opration);
            }else{
                userdetails.setJobInfo(jsonObject.get("jobInfo")==null?loginMap.get("jobInfo")==null?"":loginMap.get("jobInfo").toString():jsonObject.get("jobInfo").toString());
            }
            userdetails.setIdCard(idcode);
            userdetails.setSex(sex);
            userdetails.setBalance((long)loginMap.get("balance"));

            JSONObject rejson = iUserInfoService.updateUserData(userinfo,userdetails);
            if(rejson==null){
                json.put("statecode",2);
                json.put("msg","无法持久化您的数据");
            }else{
                json.put("statecode",0);
                json.put("msg","数据修改成功");
                //刷新session信息
                HashMap<String,Object>  drom = iUserInfoService.login(userinfo.getPhone(),userinfo.getPassword());
                request.getSession().setAttribute("drom",drom);
            }
        }
        return json.toJSONString();
    }

    //更新密码
    @RequestMapping("/changePwd")
    @ResponseBody
    public String updatePassword(@RequestParam("pwd") String newpwd,
                                 @RequestParam("randcode") String randcode,
                                 HttpServletRequest request){
        //设置传参对象
        JSONObject json = new JSONObject();
        //获取登陆用户信息
        HashMap<String,Object> loginUser = null;
        if(request.getSession().getAttribute("drom")!=null){
            loginUser = (HashMap<String, Object>) request.getSession().getAttribute("drom");

            //创建基本信息对象
            UserdetailsEntity userdetails = new UserdetailsEntity();
            userdetails.setName(loginUser.get("name")==null?null:loginUser.get("name").toString());
            userdetails.setSex(loginUser.get("sex")==null?null:(int)loginUser.get("sex"));
            userdetails.setIdCard(loginUser.get("idCard")==null?null:loginUser.get("idCard").toString());

            //验证验证码
            if(request.getSession().getAttribute("phoneRandCode")!=null){
                String timeAndRandCode = request.getSession().getAttribute("phoneRandCode").toString();
                long time = Long.parseLong(timeAndRandCode.split("#")[1]);
                long ta = new Date().getTime();
                if(((ta-time)/1000)<180){
                    if(randcode.equalsIgnoreCase(timeAndRandCode.split("#")[0])){
                        return this.updateUserData(userdetails.getName(),userdetails.getSex(),loginUser.get("phone").toString(),userdetails.getIdCard(),"{'password':'"+newpwd+"'}",request);
                    }
                }else{
                    json.put("statecode",1);
                    json.put("msg","您的验证码超时了");
                }
            }
        }else{
            json.put("statecode",1);
            json.put("msg","您没有登录，无法操作");
        }
        return json.toJSONString();
    }

    //取消预约
    @RequestMapping("/delAppoin")
    public String delAppoin(int rid,String condition,int isHouse){
        boolean bln = appoinService.delAppoin(rid, condition, isHouse);
        if(bln){
            if(isHouse==1){
                return "/renting/pages/landlord/appointment";
            }
            return "/renting/pages/tenant/appointment";
        }
        if(isHouse==1){
            return "/renting/pages/landlord/release";
        }
        return "/renting/pages/tenant/release";
    }

    //确认看房
    @RequestMapping("/updateAppoin")
    public String updateAppoin(int rid){
        boolean bln = appoinService.updateAppoin(rid);
        if(bln){
            return "/renting/pages/landlord/appointment";
        }
        return "/renting/pages/landlord/release";
    }

    //头像上传
    @RequestMapping("/userImg")
    public void saveUserImg(@RequestParam("upLoadfile") MultipartFile multipartFile,
                            HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
        String endStr = "";
        if(multipartFile==null){
            try {
                response.getWriter().write("没有图片");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ;
        }
        endStr = FileUpLoad.upFile(multipartFile,request);
        //设置传参对象
        JSONObject json = new JSONObject();
        //获取登陆用户信息
        HashMap<String,Object> loginUser = null;
        if(request.getSession().getAttribute("drom")!=null){
            loginUser = (HashMap<String, Object>) request.getSession().getAttribute("drom");

            //创建基本信息对象
            UserdetailsEntity userdetails = new UserdetailsEntity();
            userdetails.setName(loginUser.get("name")==null?null:loginUser.get("name").toString());
            userdetails.setSex(loginUser.get("sex")==null?null:(int)loginUser.get("sex"));
            userdetails.setIdCard(loginUser.get("idCard")==null?null:loginUser.get("idCard").toString());

            String tempStr = "";
            tempStr = this.updateUserData(userdetails.getName(),userdetails.getSex(),loginUser.get("phone").toString(),userdetails.getIdCard(),"{'avater':'"+endStr+"'}",request);
            //验证验证码
            if(tempStr!=null&&tempStr.length()>1){
                json.put("statecode",0);
                json.put("msg","您的头像已经更新好了");
                //刷新session信息
                HashMap<String,Object>  drom = iUserInfoService.login(loginUser.get("phone").toString(),loginUser.get("password").toString());
                request.getSession().setAttribute("drom",drom);
            }else{
                json.put("statecode",1);
                json.put("msg","网络异常，请稍后重试");
            }
        }else{
            json.put("statecode",1);
            json.put("msg","您没有登录，无法操作");
        }
        response.getWriter().write(json.toJSONString());
    }


    //实名认证
    @RequestMapping(value = "/realaction",produces = "application/json; charset=utf-8")
    public void addUserAttachment(@RequestParam(value = "filess") MultipartFile[] multipartFiles,
                                    HttpServletRequest request,
                                  HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //设置传参对象
        JSONObject json = new JSONObject();
        //设置持久化对像
        UserattachmentEntity userattachment = new UserattachmentEntity();
        //获取登录者数据
        HashMap<String,Object> loginMap;
        if(request.getSession().getAttribute("drom")!=null){
            loginMap = (HashMap<String, Object>) request.getSession().getAttribute("drom");
            //执行图片上传
            List pathList = FileUpLoad.upFiles(multipartFiles,request);
            if(pathList!=null){
                //设置持久化数据
                userattachment.setUserId((int)loginMap.get("rid"));
                userattachment.setIdCardF(pathList.get(0).toString());
                userattachment.setIdCardN(pathList.get(1).toString());
                //持久化
                if(iUserInfoService.addUserIdCaderImg(userattachment)){

                    json.put("statecode",0);
                    json.put("msg","您的身份证件已经上传成功");
                }else{
                    json.put("statecode",1);
                    json.put("msg","数据持久化失败");
                }
            }else{
                json.put("statecode",1);
                json.put("msg","图片上传失败");
            }
        }else{
            json.put("statecode",1);
            json.put("msg","您未进行登录");
        }
        response.getWriter().write(json.toJSONString());
    }

    //获取实名信息
    @RequestMapping("/getuserRealData")
    public void getUserRealDate(HttpServletRequest request,
                                HttpServletResponse response) throws IOException {
        //设置乱码处理
        response.setCharacterEncoding("utf-8");
        //设置传参对象
        JSONObject json = new JSONObject();
        //获取登录对象数据
        HashMap<String,Object> loginUser;
        if(request.getSession().getAttribute("drom")!=null){
            loginUser = (HashMap<String, Object>) request.getSession().getAttribute("drom");
            UserattachmentEntity userattachment = iUserInfoService.queryUserAchmentImg((int)loginUser.get("rid"));
            if(userattachment==null){
                json.put("statecode",1);
                json.put("msg","还未实名");
            }else{
                json.put("statecode",0);
                json.put("msg","已实名");
                json.put("data",userattachment);
            }
        }else{
            json.put("statecode",1);
            json.put("msg","您未登录");
        }
        response.getWriter().write(json.toJSONString());
    }


}
